package com.isoft.mapper;

import com.isoft.entity.DfmeCfceEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface DfmeCfceMapper {
    @Insert("INSERT INTO MSG_META(SENDER, RECEIVER, SEQUENCE_NUMBER, DATE_TIME, MSG_TYPE, SUB_TYPE) " +
            "VALUES(" +
            "#{meta.sender,jdbcType=VARCHAR}, " +
            "#{meta.receiver,jdbcType=VARCHAR}, " +
            "#{meta.sequenceNumber,jdbcType=NUMERIC}, " +
            "TO_TIMESTAMP(#{meta.dateTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'), " +
            "#{meta.type,jdbcType=VARCHAR}, " +
            "#{meta.subType,jdbcType=VARCHAR})")
    @Options(useGeneratedKeys = true, keyProperty = "meta.msgId")
    void insertMeta(DfmeCfceEntity entity);

    @Insert({
            "MERGE INTO FLIGHT_BASE fb ",
            "USING (SELECT #{dflt.flightId} AS FLIGHT_ID FROM DUAL) src ",
            "ON (fb.FLIGHT_ID = src.FLIGHT_ID) ",
            "WHEN MATCHED THEN ",
            "UPDATE SET ",
            "fb.FLIGHT_FILE_ID = #{dflt.flightFileId,jdbcType=VARCHAR}, ",
            "fb.FLIGHT_IDENTIFIER = #{dflt.flightIdentifier,jdbcType=VARCHAR} ",
            "WHEN NOT MATCHED THEN ",
            "INSERT (FLIGHT_ID, FLIGHT_FILE_ID, FLIGHT_IDENTIFIER) ",
            "VALUES (",
            "#{dflt.flightId,jdbcType=NUMERIC}, ",
            "#{dflt.flightFileId,jdbcType=VARCHAR}, ",
            "#{dflt.flightIdentifier,jdbcType=VARCHAR})"
    })
    int insertFlightBase(DfmeCfceEntity entity);

    @Select("SELECT COALESCE(MAX(AIRCRAFT_ID), 0) + 1 FROM AIRCRAFT")
    Long getNextAircraftId();

    @Insert("INSERT INTO AIRCRAFT(FLIGHT_ID, AIRCRAFT_TYPE, AIRCRAFT_NUMBER) " +
            "VALUES(" +
            "#{flightId,jdbcType=NUMERIC}, " +
            "#{aircraftType,jdbcType=VARCHAR}, " +
            "#{aircraftNumber,jdbcType=VARCHAR})")
    @Options(useGeneratedKeys = true, keyProperty = "aircraftId", keyColumn = "AIRCRAFT_ID")
    int insertAircraft(
            @Param("flightId") Long flightId,
            @Param("aircraftType") String aircraftType,
            @Param("aircraftNumber") String aircraftNumber);
}